package com.zsy.service.impl;

import com.zsy.mapper.IUserMapper;
import com.zsy.entity.User;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.security.core.authority.AuthorityUtils;
import org.springframework.security.core.userdetails.UserDetails;
import org.springframework.security.core.userdetails.UserDetailsService;
import org.springframework.security.core.userdetails.UsernameNotFoundException;
import org.springframework.stereotype.Service;

import java.util.List;
import java.util.stream.Collectors;

@Service
public class SpringUserDetailsService implements UserDetailsService {

    @Autowired
    private IUserMapper userMapper;

    @Override
    public UserDetails loadUserByUsername(String username) throws UsernameNotFoundException {
//        System.out.println("前端用户名"+username);
        User user = userMapper.selectByUsername(username);
        if(user == null){
            throw new UsernameNotFoundException("用户名不存在");
        }

        //获得用户角色列表id
        List<String> roleCodes = userMapper.selectRolesByUserId(user.getUserid());

        //通过角色列表获取权限列表
        List<String> menus = userMapper.selectMenuByRoles(roleCodes);


        roleCodes = roleCodes.stream()
                .distinct()
                .map(r->"ROLE_"+r)   //拼接为角色名
                .collect(Collectors.toList()); //转为list

        menus.addAll(roleCodes);
        System.out.println("总"+menus);
        /*
         *  将转换后的权限列表复制给user对象的authorities属性
         *  中间这部分是security提供的方法，用于将一个逗号分割的权限字符串转换为List<GrantedAuthority>
         *  String.join(",",menus)方法会将这个集合中的所有元素用逗号连接成一个单一的字符串
         */
        user.setAuthorities(AuthorityUtils.commaSeparatedStringToAuthorityList(String.join(",",menus)));
        System.out.println("用户名："+user.getUsername());
        System.out.println("密码："+user.getPassword());
        System.out.println("部门："+user.getDepartment());
        System.out.println("手机号："+user.getPhone());
        return user;
    }
}